package org.xa3apm.vote.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.jboss.logging.Logger;
import org.jboss.logging.Logger.Level;
import org.xa3apm.vote.exception.AuthenticationException;
import org.xa3apm.vote.hibernate.bean.AccountBean;
import org.xa3apm.vote.hibernate.bean.CandidateBean;
import org.xa3apm.vote.hibernate.entities.Account;
import org.xa3apm.vote.hibernate.entities.Candidate;

@ManagedBean(name = "controller")
@SessionScoped
public class Controller implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6635696689384358885L;
	@EJB
	private AccountBean accountBean;
	@EJB
	private CandidateBean candidateBean;
	@EJB
	private VoteBean voteBean;
	private Long id;
	private String userName;
	private String userPassword;
	private Account account;
	private boolean loggedIn;
	private Logger logger = Logger.getLogger(getClass());

	/**
	 * @return the id
	 */
	public final Long getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public final void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the userName
	 */
	public final String getUserName() {
		return userName;
	}

	/**
	 * @param userName
	 *            the userName to set
	 */
	public final void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * @return the userPassword
	 */
	public final String getUserPassword() {
		return userPassword;
	}

	/**
	 * @param userPassword
	 *            the userPassword to set
	 */
	public final void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public List<Candidate> getCandidates() {
		// return new
		// ArrayList<Candidate>(candidateBean.getAllBySettlement(account.getPerson().getAddress().getSettlements()));
		return new ArrayList<Candidate>(
				candidateBean.getAllByMunicipality(account.getPerson()
						.getAddress().getSettlements().getMunicipality()));
	}

	public Controller() {
		// TODO Auto-generated constructor stub
	}

	public String logIn() {
		try {
			account = accountBean.checkCredential(userName, userPassword);
			loggedIn = account != null;
		} catch (AuthenticationException e) {
			logger.logf(Level.TRACE, "Login failes", e);
			return "internalError";
		}
		if (loggedIn)
			return "loginSuccess";
		else
			return "loginFailure";
	}

	public String vote() {
		Candidate candidate = candidateBean.getById(id);
		return voteBean.saveVote(account, candidate, account.getPerson()
				.getAddress().getSettlements());
	}

	public String logOut() {
		loggedIn = false;
		return "login";
	}
}
